
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from django.conf import settings
def generate_access_token(openid):
    '''
    签名、序列化openid
    :param openid:openid明文
    :return:token(openid密文)
    '''
    # 创建序列化对象
    # s=Serializer('密钥，越复杂越安全','过期的时间')
    s = Serializer(settings.SECRET_KEY, 600)
    # 准备待序列化的字典数据
    data={'openid':openid}
    # 调用dumps方法进行序列化
    token=s.dumps(data)
    # 返回序列化后的数据
    return token.decode()

def check_access_token(access_token_openid):
    '''
    反解
    :param access_token_openid: 密文
    :return:明文
    '''
    # 创建序列化对象
    s=Serializer(settings.SECRET_KEY, 600)
    try:
        # 反序列化数据
        data=s.loads(access_token_openid)
    except BadData:
        # 数据过期
        return None
    else:
        # 返回数据
        return data.get('openid')
